/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.util;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.alipay.hessian.generic.exception.ConvertException;
import com.alipay.hessian.generic.model.GenericArray;
import com.alipay.hessian.generic.model.GenericClass;
import com.alipay.hessian.generic.model.GenericCollection;
import com.alipay.hessian.generic.model.GenericMap;
import com.alipay.hessian.generic.model.GenericObject;

/**
 * Generic object transform tool
 */
public class GenericObjectUtil {

    /**
     * Convert genericobject to concrete object
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertToObject(Object genericObject) {

        try {
            return (T) innerToConvertObject(genericObject, new IdentityHashMap<Object, Object>());
        } catch (Throwable t) {
            throw new ConvertException(t);
        }
    }

    private static Object innerToConvertObject(Object value, Map<Object, Object> map) throws Exception {

        if (value == null) {
            return null;
        }

        if (value.getClass() == GenericObject.class) {
            GenericObject genericObject = (GenericObject) value;
            return doConvertToObject(genericObject, map);
        }

        if (value.getClass() == GenericCollection.class) {
            GenericCollection collection = (GenericCollection) value;
            return doConvertToCollection(collection, map);
        }

        if (value.getClass() == GenericMap.class) {
            GenericMap genericMap = (GenericMap) value;
            return doConvertToMap(genericMap, map);
        }

        if (value.getClass() == GenericArray.class) {
            GenericArray genericArray = (GenericArray) value;
            return doConvertToArray(genericArray, map);
        }

        if (value.getClass() == GenericClass.class) {
            GenericClass genericClass = (GenericClass) value;
            return doConvertToClass(genericClass, map);
        }

        Object obj = handleCollectionOrMapToObject(value, map);
        return obj;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private static Object handleCollectionOrMapToObject(Object value, Map<Object, Object> map) throws Exception {

        if (value == null) {
            return null;
        }

        if (map.get(value) != null) {
            return map.get(value);
        }

        if (Collection.class.isAssignableFrom(value.getClass())) {

            Collection values = (Collection) value;
            Collection result = (Collection) value.getClass().newInstance();
            map.put(value, result);

            for (Object obj : values) {
                result.add(innerToConvertObject(obj, map));
            }

            return result;
        }

        if (Map.class.isAssignableFrom(value.getClass())) {

            Map<Object, Object> valueMap = (Map<Object, Object>) value;
            Map result = (Map) value.getClass().newInstance();
            map.put(value, result);

            Iterator iter = valueMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                result.put(innerToConvertObject(entry.getKey(), map), innerToConvertObject(entry.getValue(), map));
            }

            return result;
        }

        return value;
    }

    private static Object doConvertToObject(GenericObject genericObject, Map<Object, Object> map) throws Exception {

        if (genericObject == null) {
            return genericObject;
        }
        Map<String, Object> result = new HashMap<String, Object>();

        Object object = map.get(genericObject);
        if (object != null) {
            return object;
        }

        for (Entry<String, Object> entry : genericObject.getFields().entrySet()) {
            result.put(entry.getKey(), convertToObject(entry.getValue()));
        }

        return result;
    }

    private static Class<? extends Object> loadClassFromTCCL(String clazzName) throws ClassNotFoundException {
        return Class.forName(clazzName, true, Thread.currentThread().getContextClassLoader());
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private static Object doConvertToCollection(GenericCollection genericCollection, Map<Object, Object> map)
            throws Exception {

        Object object = map.get(genericCollection);
        if (object != null) {
            return object;
        }

        Class clazz = loadClassFromTCCL(genericCollection.getType());
        if (!Collection.class.isAssignableFrom(clazz)) {
            throw new IllegalArgumentException("GenericCollection实例未封装Collection实例.");
        }

        Collection result = (Collection) clazz.newInstance();
        map.put(genericCollection, result);

        Collection values = genericCollection.getCollection();
        for (Object value : values) {
            result.add(innerToConvertObject(value, map));
        }

        return result;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private static Object doConvertToMap(GenericMap genericMap, Map<Object, Object> map) throws Exception {

        Object object = map.get(genericMap);
        if (object != null) {
            return object;
        }

        Class clazz = loadClassFromTCCL(genericMap.getType());
        if (!Map.class.isAssignableFrom(clazz)) {
            throw new IllegalArgumentException("GenericMap实例未封装Map实例.");
        }

        Map result = (Map) clazz.newInstance();
        map.put(genericMap, result);

        Iterator iter = genericMap.getMap().entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            result.put(innerToConvertObject(entry.getKey(), map), innerToConvertObject(entry.getValue(), map));
        }

        return result;
    }

    @SuppressWarnings("rawtypes")
    private static Object doConvertToArray(GenericArray genericArray, Map<Object, Object> map) throws Exception {

        Object object = map.get(genericArray);
        if (object != null) {
            return object;
        }

        Class clazz = loadClassFromTCCL(genericArray.getComponentType());
        Object[] objects = genericArray.getObjects();
        Object result = Array.newInstance(clazz, objects.length);
        map.put(genericArray, result);

        for (int i = 0; i < objects.length; i++) {
            Array.set(result, i, innerToConvertObject(objects[i], map));
        }

        return result;
    }

    private static Object doConvertToClass(GenericClass genericClass, Map<Object, Object> map)
            throws ClassNotFoundException {
        Object object = map.get(genericClass);
        if (object != null) {
            return object;
        }

        Object obj = loadClassFromTCCL(genericClass.getClazzName());
        map.put(genericClass, obj);
        return obj;
    }

    @SuppressWarnings("rawtypes")
    public static GenericObject buildGenericObject(String className, Map data) {
        GenericObject object = new GenericObject(className);
        Iterator iterator = data.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Entry) iterator.next();
            object.putField((String) entry.getKey(), entry.getValue());
        }
        return object;
    }
}
